﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using ProxyHero.Entity;
using ProxyHero.HttpUility;
using System.Threading;
using LoaMen.Controls;

namespace ProxyHero.Common
{
    public class AutoChangeHelper
    {
        private DataTable dataProxy = new DataTable();
        int counts = 0;
        public AutoChangeHelper()
        {
            try
            {
                SetQueue();
            }
            catch (Exception ex)
            {
                TxtHelper.WriteLog(ex.Message);
                throw ex;
            }
        }

        private void SetQueue()
        {
            if (Config.AutoProxyQueue.Count == 0)
            {
                DataView dv = Config.AvailableProxyData.DefaultView;
                dv.Sort = "Speed";
                dataProxy = dv.ToTable();

                foreach (DataRow dr in dataProxy.Rows)
                {
                    ProxyEntity pe = new ProxyEntity();
                    pe.Ip = dr["IP"] as string;
                    pe.Port = dr["Port"] == null ? 0 : int.Parse(dr["Port"].ToString());
                    pe.Speed = dr["Speed"] == null ? 0 : double.Parse(dr["Speed"].ToString());

                    Config.AutoProxyQueue.Enqueue(pe);
                }
            }
        }

        public void ChangeProxy()
        {
            if (Config.MainForm.tsslAutoChangeProxyStatus.Text == "自动切换代理已关闭") return;
            try
            {
                if (Config.AutoProxyQueue.Count > 0)
                {
                    Config.MainForm.tsslCountdown.Text = "切换中...";
                    #region 如果有代理队列
                    ProxyEntity pe = Config.AutoProxyQueue.Dequeue();
                    TestEntity te = Config.LocalConfig.DefaultTestUrl;

                    if (te == null)
                    {
                        te = new TestEntity();
                    }

                    object[] result = HttpHelper.TestProxy(pe, te);
                    bool canUse = (bool)result[0];
                    double speed = double.Parse(result[1].ToString());

                    if (canUse)
                    {
                        #region 更换代理
                        if (speed < Config.LocalConfig.AutoProxySpeed * 1000)
                        {
                            if (Config.ProxyApplicatioin == "IE")
                            {
                                ProxyHelper ph = new ProxyHelper();
                                ph.SetIEProxy(pe.IpAndPort, 1);
                                Config.MainForm.SetProxyStatusLabel();
                            }
                            else
                            {
                                SetBrowserProxy(pe.IpAndPort);
                            }
                            Config.TsCountDown = new TimeSpan(0, Config.LocalConfig.AutoChangeProxyInterval, 0);
                            Config.MainForm.timerAutoChangeProxy.Start();
                        }
                        else
                        {
                            Config.MainForm.tsslCountdown.Text = "速度不符合要求，切换中...";
                            Config.MainForm.SetToolTipText("代理" + pe.IpAndPort + "速度不符合要求，自动切换下一代理。");
                            Thread.Sleep(1000);
                            ChangeProxy();
                        }
                        #endregion
                    }
                    else
                    {
                        #region 经验证代理已失效
                        Config.MainForm.tsslCountdown.Text = "代理无效，切换中...";
                        Config.AvailableProxyData.Rows.Remove(Config.AvailableProxyData.Rows.Find(new object[] { pe.Ip, pe.Port }));
                        Config.ProxyViewForm.BindDataGrid();
                        Config.MainForm.SetToolTipText("代理" + pe.IpAndPort + "无效，自动切换下一代理。");
                        Thread.Sleep(1000);
                        ChangeProxy();
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    if (counts < 20) //如果队列为空，自动设置队列20次停止
                    {
                        SetQueue();
                        counts++;
                    }
                    else
                    {
                        Config.ProxyViewForm.StopAutoChange();
                        Config.MainForm.tsslCountdown.Text = string.Empty;
                        TxtHelper.WriteLog("可用代理列表为空，无法自动切换代理。");
                        Config.MainForm.SetToolTipText("可用列表为空，无法自动切换代理。");
                    }
                }
            }
            catch (Exception ex)
            {
                TxtHelper.WriteLog(ex.Message);
                Thread.Sleep(3000);
                ChangeProxy();
            }
        }

        public void SetBrowserProxy(string proxyServer)
        {
            foreach (WebBrowserEx wbe in Config.WebBrowserArr)
            {
                wbe.ProxyServer = proxyServer;
            }
        }
    }
}